package com.huixin.zhang.common.utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;

public class WebUtils {

	/**
	 * createQueryString 构造签名
	 * @param params
	 * @param encode
	 * @return
	 */
	public static String createQueryString(Map<String, String> params, boolean encode) {
		Set<String> keysSet = params.keySet();
		Object[] keys = keysSet.toArray();
		Arrays.sort(keys);
		StringBuilder builder = new StringBuilder();
		for (Object key : keys) {
			if (builder.length() > 0) {
				builder.append("&");
			}
			builder.append(key).append("=");
			Object value = params.get(key);
			String valueString = "";
			if (value != null) {
				valueString = value.toString();
			}
			if (encode) {
				builder.append(TextUtils.toUtf8Encode(valueString));
			} else {
				builder.append(valueString);
			}
		}
		return builder.toString();
	}

	public static HttpServletRequest getRequest(){
		HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
		return request;
	}

	public static String getIpAddr() {
		HttpServletRequest request = getRequest();
		String ipAddress = request.getHeader("x-forwarded-for");
		try {
			if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
				ipAddress = request.getHeader("Proxy-Client-IP");
			}
			if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
				ipAddress = request.getHeader("WL-Proxy-Client-IP");
			}
			if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
				ipAddress = request.getRemoteAddr();
				if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
					InetAddress inet = InetAddress.getLocalHost();
					ipAddress = inet.getHostAddress();
				}
			}
			if (ipAddress != null && ipAddress.length() > 15) {
				if (ipAddress.indexOf(",") > 0) {
					ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
				}
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return ipAddress;
	}
}
